import type { permItem } from '@/store/type'
/**
 * 树形路由节点接口，继承基础路由节点并添加children属性
 */
interface TreeRouteNode extends permItem {
  children: TreeRouteNode[]
}
// 递归排序树形路由
function sortTreeRouteNodes(treeRoutes: TreeRouteNode[]) {
  if (!treeRoutes.length) {
    return
  }
  treeRoutes.sort((a, b) => {
    return a.sortOrder - b.sortOrder
  })
  treeRoutes.forEach((node) => {
    node.children.sort((a, b) => {
      return a.sortOrder - b.sortOrder
    })
    sortTreeRouteNodes(node.children)
  })
}

/**
 * 将平级路由数组转换为树形结构,并排序
 * @param flatRoutes - 平级的路由数组
 * @returns 树形结构的路由数组
 */
function convertToTree(flatRoutes: permItem[]): TreeRouteNode[] {
  const treeRoutes: TreeRouteNode[] = []
  const routeMap: Map<string, TreeRouteNode> = new Map()
  flatRoutes.forEach((route) => {
    routeMap.set(route.id!, { ...route, children: [] })
  })
  flatRoutes.forEach((route) => {
    const parent = route.parentId
    if (parent && routeMap.has(parent)) {
      routeMap.get(parent)!.children.push(routeMap.get(route.id!)!)
    }
    else {
      treeRoutes.push(routeMap.get(route.id!)!)
    }
  })
  sortTreeRouteNodes(treeRoutes)

  return treeRoutes
}
interface EventOption {
  name: string
  des: string
  code: string
}
function convertOptionsForCodeMirror(options: { event: EventOption[], attrs: Record<string, any> }): { events: string, attrs: string } {
  // 处理事件数组 - 将每个事件的code转换为字符串
  const eventsStr = options.event.map((event) => {
    // 移除TypeScript类型注解
    const codeStr = event.code.toString().replace(/:\s*\w+/g, '')
    return `{
  name: '${event.name}',
  des: '${event.des}',
  code: ${codeStr}
}`
  }).join(',\n')

  // 处理属性对象 - 转换为简洁的对象字面量
  const attrsStr = JSON.stringify(options.attrs, null, 2)
    .replace(/"([^"]+)":/g, '$1:') // 移除键名引号
    .replace(/"/g, '\'') // 双引号转单引号

  // 组合成完整的格式
  return {
    events: `[\n${eventsStr}\n]`,
    attrs: attrsStr,
  }
}

export { convertOptionsForCodeMirror, convertToTree, type permItem, type TreeRouteNode }
